import service from "@/axios/axios";
import { Notification } from "element-ui";
import Vue from "vue";
import { client } from "./oss";

function $(selector) {
  const nodeList = document.querySelectorAll(selector);
  return nodeList.length === 1 ? nodeList[0] : nodeList;
}

function deepClone(data) {
  return JSON.parse(JSON.stringify(data));
}

function downLoadFile(apiSetting, fileName,loading) {
  service({
    ...apiSetting,
    responseType: "blob"
  }).then(res => {
    if (!(res instanceof Blob) || res.type === "application/json") {
      res.text().then(res => {
        Notification.error(JSON.parse(res).msg);
      });
      return;
    }
		if(loading){
			//如果有下载成功弹窗
			loading.close();
		}
    const a = document.createElement("a");
    a.download = fileName;
    a.href = URL.createObjectURL(res);
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(a.href);
    document.body.removeChild(a);
  });
}

function generateId() {
  return Number(
    Math.random()
      .toString()
      .substr(3, length) + Date.now()
  ).toString(36);
}

function uploadFile(pathKey, file, progress = () => {}) {
  const uploadPath = {
    avatar: "exam/Resources/Avatars/",
    course: "exam/Resources/Course/"
  };
  const { name } = file;
  //文件后缀
  const suffix = name.substring(name.lastIndexOf("."), name.length);
  const fileName = generateId();
  return client.multipartUpload(
    `${uploadPath[pathKey]}${fileName}${suffix}`,
    file,
    {
      progress: p => {
        progress(parseInt((p * 100).toFixed(2)));
      }
    }
  );
}

function verifyFile(file, type, limit) {
  const MB = 1024 * 1024;
  const fileType = {
    video: new RegExp(/video\/mp4|video\/ogg|image\/webm/),
    image: new RegExp(/image\/jpeg|image\/png|image\/jpg/)
  };
  if (fileType[type].test(file.raw.type) === false) return "文件格式错误！";
  if (file.size / MB > limit) return `最大上传不能超过${limit}M！`;
  return true;
}

function isInVue() {
  return this instanceof Vue;
}

export default {
  $,
  deepClone,
  downLoadFile,
  uploadFile,
  verifyFile,
  isInVue
};
